package relaychat.server;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.*;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 * 
 * EmbeddedJettyServer
 * This class impements the jetty server and sets up the context for running the chat program.
 *
 */
public class EmbeddedJettyServer {

	/**
	 * main class
	 * Called when the program is started
	 * @param args
	 */
	public static void main(String[] args) {
		 String currDir = "";
		 Server server = new Server();
         Connector connector = new SelectChannelConnector();
         
         //allows the war to be deployed on other computers by getting the local host.
         java.net.InetAddress i;
         try {
			i = java.net.InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			i = null;
		}

         
         connector.setHost(i.getHostName());
         //Check args to see if a port number was passed into the program
         if(args.length == 0){
        	 connector.setPort(8090);
         } else{
        	 System.out.println(args[0]);
        	 try { 
        		 connector.setPort(Integer.parseInt(args[0])); 
        	    } catch(Exception e) { 
        	    	 connector.setPort(8090);
        	    }	 
         }
         server.addConnector(connector);
         
         //The context for the web app set path to local files for eclipse start
         //and set war to external form for embeddable server.
         WebAppContext wac = new WebAppContext();
         try {
			currDir = new File(".").getCanonicalPath().toString();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
         //comment out to build stand alone war using mvn install command
         wac.setDescriptor(currDir+"/src/main/webapp/WEB-INF/web.xml");
         wac.setResourceBase(currDir+"/src/main/webapp");
         wac.setContextPath("/");
         wac.setParentLoaderPriority(true);
         
         //Used to build stand alone war uncomment for build 
         //URL location = EmbeddedJettyServer.class.getProtectionDomain().getCodeSource().getLocation();
         //wac.setWar(location.toExternalForm());
         
         server.setHandler(wac);
         try {
             server.start();
             //used to build stand alone war and shut down server uncomment for build
             //System.in.read();
             //server.stop();
             //server.join();
           } catch (Exception e) {
        	   System.out.println("server start issue");
           }

	}

}
